package com.student.view;

import com.student.util.Constant;

import javax.swing.*;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;


import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.BufferedWriter;
import java.io.FileWriter;

public class RandomGroupPanel extends JPanel {
    private JLabel lbl1 = new JLabel("小组名：");
    private JLabel lbl2 = new JLabel("学生姓名：");
    private JLabel lbl3 = new JLabel("学生照片：");
    private JLabel lblPic = new JLabel("照片");
    private JLabel lbl4 = new JLabel("小组评分");
    private JTextField txtGroup = new JTextField();
    private JTextField txtStudent = new JTextField();
    private JTextField txtScore = new JTextField();
    private JButton btnChooseGroup = new JButton("随机小组");
    private JButton btnChooseStudent = new JButton("随机学生");
    private JButton btnAbsence = new JButton("缺勤");
    private JButton btnLeave = new JButton("请假");
    private JButton btnScore = new JButton("小组评分");
    Thread threadGroup = null;   // 随机抽取小组的线程
    Thread threadStudent = null;   // 随机抽取学生的线程

    public RandomGroupPanel() {
        this.setBorder(new TitledBorder(new EtchedBorder(), "随机小组点名"));
        this.setLayout(null);
        this.add(lbl1);
        this.add(lbl2);
        this.add(lbl3);
        this.add(txtGroup);
        this.add(txtStudent);
        this.add(lblPic);
        this.add(btnChooseGroup);
        this.add(btnChooseStudent);
        this.add(btnAbsence);
        this.add(btnLeave);
        this.add(lbl4);
        this.add(txtScore);
        this.add(btnScore);

        lbl1.setBounds(50, 50, 100, 30);
        txtGroup.setBounds(50, 90, 100, 30);
        txtGroup.setEditable(false);
        btnChooseGroup.setBounds(50, 130, 100, 30);

        lbl4.setBounds(50, 190, 100, 30);
        txtScore.setBounds(50, 230, 100, 30);
        btnScore.setBounds(50, 270, 100, 30);

        lbl2.setBounds(220, 50, 100, 30);
        txtStudent.setBounds(220, 90, 130, 30);
        txtStudent.setEditable(false);
        lblPic.setBounds(220, 130, 130, 150);
        btnChooseStudent.setBounds(220, 300, 100, 30);
        btnAbsence.setBounds(220, 340, 60, 30);
        btnLeave.setBounds(290, 340, 60, 30);
        // 添加按钮功能
        // 随机小组
        btnChooseGroup.addActionListener(e -> {
            if (e.getActionCommand().equals("停")) {
                btnChooseGroup.setText("随机小组");
                if (threadGroup != null) {
                    threadGroup.interrupt();
                    threadGroup = null;
                }
            } else {
                btnChooseGroup.setText("停");
                threadGroup = new Thread(() -> {
                    try {
                        // 读取小组文件
                        String groupFilePath = Constant.classesPath + "\\" + Constant.CLASS_PATH + Constant.groupsPath;
                        List<String> groupNames = new ArrayList<>();

                        try (BufferedReader reader = new BufferedReader(new FileReader(groupFilePath))) {
                            String line;
                            while ((line = reader.readLine()) != null) {
                                String[] fields = line.split("，");
                                if (fields.length == 4) {
                                    groupNames.add(fields[1]); // 添加小组名称
                                }
                            }
                        } catch (IOException ex) {
                            SwingUtilities.invokeLater(() -> {
                                JOptionPane.showMessageDialog(this, "读取小组信息失败", "", JOptionPane.ERROR_MESSAGE);
                                btnChooseGroup.setText("随机小组");
                            });
                            return;
                        }

                        if (groupNames.isEmpty()) {
                            SwingUtilities.invokeLater(() -> {
                                JOptionPane.showMessageDialog(this, "当前班级没有小组信息", "", JOptionPane.INFORMATION_MESSAGE);
                                btnChooseGroup.setText("随机小组");
                            });
                            return;
                        }

                        while (!Thread.interrupted()) {
                            // 随机选择一个小组
                            int index = new Random().nextInt(groupNames.size());
                            String groupName = groupNames.get(index);
                            SwingUtilities.invokeLater(() -> txtGroup.setText(groupName));
                            Thread.sleep(100); // 控制滚动速度
                        }
                    } catch (InterruptedException ex) {
                        // 线程被中断时的处理
                    }
                });
                threadGroup.start();
            }
        });
        // 随机学生
        btnChooseStudent.addActionListener(e -> {
            if (txtGroup.getText() == null || txtGroup.getText().isEmpty()) {
                JOptionPane.showMessageDialog(this, "请先随机抽取小组", "", JOptionPane.INFORMATION_MESSAGE);
            } else {
                if (e.getActionCommand().equals("停")) {
                    btnChooseStudent.setText("随机学生");
                    if (threadStudent != null) {
                        threadStudent.interrupt();
                        threadStudent = null;
                    }
                } else {
                    btnChooseStudent.setText("停");
                    threadStudent = new Thread(() -> {
                        try {
                            // 读取学生文件，获取当前小组的学生
                            String studentFilePath = Constant.classesPath + "\\" + Constant.CLASS_PATH + Constant.studentsPath;
                            List<String> groupStudents = new ArrayList<>();

                            try (BufferedReader reader = new BufferedReader(new FileReader(studentFilePath))) {
                                String line;
                                while ((line = reader.readLine()) != null) {
                                    String[] fields = line.split("，");
                                    if (fields.length == 4 && fields[3].equals(txtGroup.getText())) {
                                        groupStudents.add(fields[1]); // 添加学生姓名
                                    }
                                }
                            } catch (IOException ex) {
                                SwingUtilities.invokeLater(() -> {
                                    JOptionPane.showMessageDialog(this, "读取学生信息失败", "", JOptionPane.ERROR_MESSAGE);
                                    btnChooseStudent.setText("随机学生");
                                });
                                return;
                            }

                            if (groupStudents.isEmpty()) {
                                SwingUtilities.invokeLater(() -> {
                                    JOptionPane.showMessageDialog(this, "当前小组没有学生", "", JOptionPane.INFORMATION_MESSAGE);
                                    btnChooseStudent.setText("随机学生");
                                });
                                return;
                            }

                            while (!Thread.interrupted()) {
                                int index = new Random().nextInt(groupStudents.size());
                                String studentName = groupStudents.get(index);
                                SwingUtilities.invokeLater(() -> txtStudent.setText(studentName));
                                Thread.sleep(100);
                            }
                        } catch (InterruptedException ex) {
                            // 线程被中断时的处理
                        }
                    });
                    threadStudent.start();
                }
            }
        });

        // TODO 缺勤
        btnAbsence.addActionListener(e -> {
            if (txtStudent.getText() == null || txtStudent.getText().isEmpty()) {
                JOptionPane.showMessageDialog(this, "请先随机选择学生", "", JOptionPane.INFORMATION_MESSAGE);
            } else {
                updateGroupScore(Constant.ABSENTEEISM_SCORE, "缺勤");
            }
        });
        // TODO 请假
        btnLeave.addActionListener(e -> {
            if (txtStudent.getText() == null || txtStudent.getText().isEmpty()) {
                JOptionPane.showMessageDialog(this, "请先随机选择学生", "", JOptionPane.INFORMATION_MESSAGE);
            } else {
                updateGroupScore(Constant.LEAVE_SCORE, "请假");
            }
        });

        // TODO 给小组打分
        btnScore.addActionListener(e -> {
            if (txtGroup.getText() == null || txtGroup.getText().isEmpty()) {
                JOptionPane.showMessageDialog(this, "请先抽取小组", "", JOptionPane.INFORMATION_MESSAGE);
                return;
            }
            if (txtScore.getText() == null || txtScore.getText().isEmpty()) {
                JOptionPane.showMessageDialog(this, "请填写分数", "", JOptionPane.INFORMATION_MESSAGE);
                return;
            }

            // 验证分数格式
            try {
                float score = Float.parseFloat(txtScore.getText());
                if (score < 0 || score > 100) {
                    JOptionPane.showMessageDialog(this, "请输入有效分数", "", JOptionPane.ERROR_MESSAGE);
                    return;
                }
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(this, "请输入有效分数", "", JOptionPane.ERROR_MESSAGE);
                return;
            }

            // 更新文件中的分数
            String groupFilePath = Constant.classesPath + "\\" + Constant.CLASS_PATH + Constant.groupsPath;
            List<String> lines = new ArrayList<>();
            boolean found = false;

            try {
                // 读取所有行
                try (BufferedReader reader = new BufferedReader(new FileReader(groupFilePath))) {
                    String line;
                    while ((line = reader.readLine()) != null) {
                        String[] fields = line.split("，");
                        if (fields.length ==4 && fields[1].equals(txtGroup.getText())) {
                            // 找到匹配的小组，更新分数
                            fields[2] = txtScore.getText();
                            line = String.join("，", fields);
                            found = true;
                        }
                        lines.add(line);
                    }
                }

                if (!found) {
                    JOptionPane.showMessageDialog(this, "未找到小组信息", "", JOptionPane.ERROR_MESSAGE);
                    return;
                }

                // 写回文件
                try (BufferedWriter writer = new BufferedWriter(new FileWriter(groupFilePath))) {
                    for (String line : lines) {
                        writer.write(line);
                        writer.newLine();
                    }
                }

                JOptionPane.showMessageDialog(this, "评分成功", "", JOptionPane.INFORMATION_MESSAGE);

            } catch (IOException ex) {
                JOptionPane.showMessageDialog(this, "更新分数失败: " + ex.getMessage(), "", JOptionPane.ERROR_MESSAGE);
            }
        });
    }
    public void updateGroupScore(int deduction,String casetype) {
        String groupFilePath = Constant.classesPath + "\\" + Constant.CLASS_PATH + Constant.groupsPath;
        List<String> lines = new ArrayList<>();
        boolean found = false;

        try {
            // 读取所有行
            try (BufferedReader reader = new BufferedReader(new FileReader(groupFilePath))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    String[] fields = line.split("，");
                    if (fields.length ==4 && fields[1].equals(txtGroup.getText())) {
                        // 找到匹配的小组，更新分数
                        int currentScore = Integer.parseInt(fields[2]);
                        int newScore = Math.max(0, currentScore - deduction); // 确保分数不小于0
                        fields[2] = String.valueOf(newScore);
                        line = String.join("，", fields);
                        found = true;
                    }
                    lines.add(line);
                }
            }

            if (!found) {
                JOptionPane.showMessageDialog(this, "未找到小组信息", "", JOptionPane.ERROR_MESSAGE);
                return;
            }
            // 写回文件
            try (BufferedWriter writer = new BufferedWriter(new FileWriter(groupFilePath))) {
                for (String line : lines) {
                    writer.write(line);
                    writer.newLine();
                }
            }
            JOptionPane.showMessageDialog(this, "已记录" + casetype + "，小组分数扣除" + deduction + "分", "",
                    JOptionPane.INFORMATION_MESSAGE);
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(this, "更新分数失败: " + ex.getMessage(), "", JOptionPane.ERROR_MESSAGE);
        }
    }
}
